package org.nimi317.web_gis.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.IoUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.nimi317.web_gis.Enum.InterpolateEnum;
import org.nimi317.web_gis.exception.E;
import org.nimi317.web_gis.exception.RException;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;

import static java.util.Calendar.MONTH;

/**
 * @author thunderobot
 */
@Component
@Slf4j
public class ImageUtils {

    private final String basePath = "/usr/src/web_gis/web_gis_vite/dist/assets";

    private final String baseFolder = "interpolate";

    private final ImageUtils utils;

    public ImageUtils(@Lazy ImageUtils utils) {
        this.utils = utils;
    }

//    @Async
    public void saveImage(MultipartFile file, String path) throws IOException {
        File newFile = new File(path);
        //检查如果路径文件夹不存在则创建
        File parentFile = newFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        FileOutputStream stream = new FileOutputStream(newFile);
        stream.write(file.getBytes());
        IoUtil.close(stream);
    }

    public String createImageName(InputStream stream, Date time) {
        String type = FileTypeUtil.getType(stream);
        if ("png".equals(type)) {
            String format = "yyyy-MM-dd HH";
            String formatted = DateUtil.format(time, format);
            return formatted + "." + type;
        } else {
            throw new RException(E.ImageTypeException);
        }
    }

    @SneakyThrows
    public String save(MultipartFile file, InterpolateEnum interpolateEnum, Date time, Integer paramId) {
        //文件路径由六部分组成 base/type/param/year/month/day/name.xxx
        InputStream stream = file.getInputStream();
        String lowerCase = interpolateEnum.toString().toLowerCase();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        String year = String.valueOf(calendar.get(Calendar.YEAR));
        String month = String.valueOf(calendar.get(MONTH));
        String day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
        String imageName = createImageName(stream, time);
        String url = "/" + baseFolder +
                "/" + lowerCase +
                "/" + paramId +
                "/" + year +
                "/" + month +
                "/" + day +
                "/" + imageName;
        String s = basePath + url;
        utils.saveImage(file, s);
        return url;
    }
}
